package com.wufeng.mycode;

import java.util.concurrent.*;

/**
 * @author niuyq
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
//         创建缓存线程池 有需要就创建线程 最大线程数为int最大值
//        corePoolSize:0,maximumPoolSize:int.maxSize,
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.submit(() -> {
                System.out.println(Thread.currentThread().getName());
            });
        }
        executorService.shutdown();

        // 创建固定数量的线程池  核心线程数和最大线程数都为固定值，阻塞队列最大值int最大值
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);
        executorService1.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "\t 当前线程");
            }
        });
        executorService1.shutdown();

        // 创建单线程线程池  核心线程数、最大线程数 为1，阻塞队列最大值int最大值
        ExecutorService executorService2 = Executors.newSingleThreadExecutor();
        executorService2.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "\t 当前线程");
            }
        });
        executorService2.shutdown();

        /**
         * public ScheduledFuture<?> schedule(Runnable command,
         *                        long delay, TimeUnit unit);
         * command：执行的任务 Callable或Runnable接口实现类
         * delay：延时执行任务的时间
         * unit：延迟时间单位
         */
        ScheduledExecutorService executorService3 = Executors.newScheduledThreadPool(10);
        ScheduledFuture<String> scheduledFuture= executorService3.schedule(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "call";
            }
        }, 10,TimeUnit.SECONDS);
        try {
            System.out.println(scheduledFuture.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executorService3.shutdown();
    }
}
